import allure
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    _Base_URL = ""
    def __init__(self,base_driver = None):
        # driver 复用
        if base_driver:
            self.driver =base_driver
        else:
            # 如果driver 为None ，则创建一个新的driver
            self.driver = webdriver.Chrome()
            # 全局等待
            self.driver.implicitly_wait(5)
            self.driver.maximize_window()

        if not self.driver.current_url.startswith("http"):
            self.driver.get(self._Base_URL)

    def find(self,by,locator=None):
        """查找元素"""
        if locator:
            return self.driver.find_element(by, locator)
        else:
            # by = (By.ID, "xxxx")
            return self.driver.find_element(*by)

    def find_and_click(self,by,locator=None):
        """查找到元素之后完成点击"""
        self.find(by,locator).click()

    def find_and_send(self,text, by,locator=None):
        """查找到元素之后完成点击"""
        self.find(by,locator).send_keys(text)

    def wait_for_visible(self, locator):
        WebDriverWait(self.driver, 10, 2).until(expected_conditions.visibility_of_element_located(locator))

    def get_text(self, by,locator):
        return self.find(by,locator).text

    def save_screen(self):
        """保存图片"""
        image_path = "../images/tmp.png"
        self.driver.save_screenshot(image_path)
        allure.attach.file(image_path, name="页面截图",attachment_type=allure.attachment_type.PNG)
